/*global Aredis, Adebug */

const search = require('feathers-mongodb-fuzzy-search')
const bcrypt = require('bcrypt')
const Acan = require('../../libs/Acan')
const errors = require('@feathersjs/errors')

// 更新最新权限到缓存
const upToRedis = (d) => {
  const rs = d.result
  if (d.method !== 'find') rs._id = rs._id.toString()
  if (d.method === 'remove') {
    return Aredis.hdel('admins', rs._id)
  } else if (['update', 'patch', 'create'].indexOf(d.method) !== -1){
    Adebug.log(d.method, 'update user')
    if (rs.del === true) return Aredis.hdel('admins', rs._id)
    oneFormat(rs)
    Aredis.hset('admins', rs._id, JSON.stringify(rs))
  }
}

// 格式化
const oneFormat = function (doc, type) {
  if (doc.last && doc.last.login) {
    doc.last.login = Acan.time('Y-m-d H:i', doc.last.login)
  }
  if (type !== 'account') {
    delete doc.password
  }
  delete doc.del
  delete doc.__v
}

// 用户更新验证
const rules = {
  mobile: post=> {
    if (!/1(3|4|5|7|8|9)[\d]{9}/.test(post.mobile)) return new errors.BadRequest('手机号码格式错误', {code: 31001, param: 'mobile'})
  },
  password: post=> {
    if (!post.password) return
    if (post.password.length < 6) return new errors.BadRequest('密码不足6位', {code: 31001, param: 'password'})
    post.password = bcrypt.hashSync(post.password, bcrypt.genSaltSync(10))
    // if (!post.password2) return new errors.BadRequest('请输入确认密码', {param: 'password2'})
  },
  password2: post=> {
    if (post.password2 !== post.password) return new errors.BadRequest('确认密码不一致', {param: 'password2'})
    post.password = bcrypt.hashSync(post.password, bcrypt.genSaltSync(10))
  }
}

// 更新用户信息
const upDo = function (d) {
  let post = d.data
  let error
  let codes = ['mobile', 'mail', 'password', 'role', 'status']

  // 移除非提交属性
  Object.keys(post).forEach(function (key) {
    if (codes.indexOf(key) === -1) delete post[key]
  })
  codes.forEach(v => {
    if (error) return
    // 密码为空不保存
    if (v === 'password' && post[v] === '') return delete post[v]
    if (rules[v] && post[v]) error = rules[v](post)
  })
  if (error) return Promise.reject(error)
}

module.exports = {
  before: {
    all: [],
    find: [ d=> {
      var get = d.params.query
      if (d.params.type !== 'account') {
        if (get && get.username) get.username = {$search: get.username}
      }
    }, search({
      fields: ['username']
    }) ],
    get: [],
    create: [ d=> {
      let post = d.data
      let error
      let codes = ['username', 'mobile', 'password', 'role']
      let zhrr = ['用户名', '手机号码', '密码', '确认密码', '角色']
      codes.forEach((v, i)=> {
        if (error) return
        if (!post[v]) return error = new errors.BadRequest('请输入' + zhrr[i], {code: 31000, param: v})
        if (rules[v]) error = rules[v](post)
      })
      if (error) return Promise.reject(error)
    }],
    update: [ upDo ],
    patch: [ upDo ],
    remove: []
  },

  after: {
    all: [upToRedis],
    find: [ d=> {
      if (!d.result.data) return
      d.result.data.forEach(doc => {
        oneFormat(doc, d.params.type)
      })
    } ],
    get: [ d=> {
      var doc = d.result
      oneFormat(doc, d.params.type)
    } ],
    create: [ d=> {
      delete d.result.password
    } ],
    update: [ d=> {
      delete d.result.password
    } ],
    patch: [ d=> {
      delete d.result.password
    } ],
    remove: []
  },

  error: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  }
}
